//
//  NetworkUtils.m
//  RTMKitDemo
//
//  Created by reyzhang on 2021/12/30.
//

#import "NetworkUtils.h"
#import <AFNetworking/AFNetworking.h>

@implementation NetworkUtils
+ (void)configManager:(AFHTTPSessionManager *)manager {
    //设置加载时间
    manager.requestSerializer.timeoutInterval = TIMEOUT;
    
    NSString *token =  nil;
    if (token.length > 0) {
        [manager.requestSerializer setValue:token forHTTPHeaderField:@"Authorization"];
    }
}


#pragma mark 请求数据传递方式为form-data格式
+ (void)get:(NSString *)url parameters:(NSDictionary *)parameters succes:(RTMSuccessBlock)success failure:(RTMFailureBlock)failure {
    [self requestWithMethod:HTTPMethodGET url:url parameters:parameters succes:success failure:failure];
}



+ (void)post:(NSString *)url parameters:(NSDictionary *)parameters succes:(RTMSuccessBlock)success failure:(RTMFailureBlock)failure {
    [self requestWithMethod:HTTPMethodPOST url:url parameters:parameters succes:success failure:failure];
}


/**
 请求数据为form-data格式
 */
+ (void)requestWithMethod:(NetworkHTTPMethod)method url:(NSString *)url parameters:(NSDictionary *)parameters succes:(RTMSuccessBlock)success failure:(RTMFailureBlock)failure{
    
    AFHTTPSessionManager * manager = [[AFHTTPSessionManager alloc] init];
    [self configManager:manager];
    
    
    //    [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    //设置请求返回的数据格式
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain", @"text/html", @"application/json",@"multipart/form-data",@"application/x-www-form-urlencoded", nil];
    
    
    NSURLSession *managerSession = manager.session;
    if (method == HTTPMethodPOST) {
        
        [manager POST:url parameters:parameters headers:@{} progress:^(NSProgress * _Nonnull uploadProgress) {
            nil;
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            if (success) {
                success(responseObject);
            }
            
            //解决AFHttpSessionManager和NSURLSession 之间的循环引用问题 reyzhang
            [managerSession finishTasksAndInvalidate];
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
            if (failure) {
                failure(error);
            }
            [managerSession finishTasksAndInvalidate];
        }];
    }else if (method == HTTPMethodGET) {
        [manager GET:url parameters:parameters headers:@{} progress:^(NSProgress * _Nonnull downloadProgress) {
            nil;
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            if (success) {
                success(responseObject);
            }
            [managerSession finishTasksAndInvalidate];
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            if (failure) {
                failure(error);
            }
            [managerSession finishTasksAndInvalidate];
        }];
    }
    
    
}



#pragma mark 请求数据传递方式为json格式
+ (void)getjson:(NSString *)url parameters:(NSDictionary *)parameters succes:(RTMSuccessBlock)success failure:(RTMFailureBlock)failure  {
    [self jsonRequestWithMethod:HTTPMethodGET url:url parameters:parameters succes:success failure:failure];
}

//body里面有json串
+ (void)postjson:(NSString *)url parameters:(NSDictionary *)parameters succes:(RTMSuccessBlock)success failure:(RTMFailureBlock)failure {
    [self jsonRequestWithMethod:HTTPMethodPOST url:url parameters:parameters succes:success failure:failure];
}

/**
 请求数据为json格式
 */
+ (void)jsonRequestWithMethod:(NetworkHTTPMethod)method url:(NSString *)url parameters:(NSDictionary *)parameters succes:(RTMSuccessBlock)success failure:(RTMFailureBlock)failure {
    
    AFHTTPSessionManager * manager = [[AFHTTPSessionManager alloc] init];
    
    //body里面含有json串填写这个
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [self configManager:manager];
    
    NSString *methodStr = method == HTTPMethodPOST ? @"POST" : @"GET";
    [manager.requestSerializer requestWithMethod:methodStr URLString:url parameters:parameters error:nil];
    
    //设置请求返回的数据格式
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/json", @"text/html", @"text/javascript", nil];
    
    NSURLSession *managerSession = manager.session;
    if (method == HTTPMethodPOST) {
        [manager POST:url parameters:parameters headers:@{} progress:^(NSProgress * _Nonnull uploadProgress) {
            nil;
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            if (success) {
                success(responseObject);
            }
            [managerSession finishTasksAndInvalidate];
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            if (failure) {
                failure(error);
            }
            [managerSession finishTasksAndInvalidate];
        }];
    }else {
        [manager GET:url parameters:parameters headers:@{} progress:^(NSProgress * _Nonnull uploadProgress) {
            nil;
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            if (success) {
                success(responseObject);
            }
            [managerSession finishTasksAndInvalidate];
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            if (failure) {
                failure(error);
            }
            [managerSession finishTasksAndInvalidate];
        }];
    }
    
}


//这是个字典转json数据的方法
+(NSString *)convertToJsonData:(NSDictionary *)dict{
    
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
    NSString *jsonString;
    if (!jsonData) {
        NSLog(@"%@",error);
    }else{
        jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
    }
    
    NSMutableString *mutStr = [NSMutableString stringWithString:jsonString];
    return mutStr;
    
}

@end
